<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/21 0021
 * Time: 上午 9:32
 */

namespace Admin\Model;


use Think\Model;

class OrderModel extends Model
{
   /* protected $insertFields = array('shr_name','shr_tel','shr_province','shr_city','shr_area','shr_address');
    protected $_validate =array(
        array('shr_name','require','收货人姓名不能为空',1,'regex',3),
        array('shr_tel','require','收人电话不能为空',1,'regex',3),
        array('shr_province','require','所在省不能为空',1,'regex',3),
        array('shr_city','require','所在城市不能为空',1,'regex',3),
        array('shr_area','require','所在地区不能为空',1,'regex',3),
        array('shr_address','require','详细地址不能为空',1,'regex',3),
    );
   */
   protected $insertFields = array('inv_payee','inv_content');
    protected function _before_insert(&$data,&$option){
        $memberId = session('m_id');
        if(!$memberId){
            $this->error='必须先登录';
            return FALSE;
        }
            $cartModel = D('Admin/Cart');
            $option['goods'] = $goods = $cartModel->cartList();
            if(!$goods){
                $this->error ='购物侧没有商品，无法下单!';
                return FALSE;
            }
            $this->fp = fopen('./order.lock');
            flock($this->fp,LOCK_EX);
            $gnModel = D('goods_number');
            $total_price = 0;
            foreach($goods as $k => $v){
                $gnNumber = $gnModel->field('goods_number')->where(array(

                ))->find();

            if($gnNumber['goods_number'] < $v['goods_number']){
                $this->error = '下单失败，原因：商品<strong>'.$v['goods_name'].'<strong> 库存量不足！';
                return FALSE;
                 }
                $total_price += $v['price'] * $v['goods_number'];
            }
            //把其他信息补到订单中
            $data['order_sn'] = self::get_order_sn();
            $data['total_price'] = $memberId;
            $data['addtime'] = time();
            //收货地址
            $address_id = I('post.address_id',0);
            if($address_id){
                $addressModel = D('Admin/UserAddress');
                $addressData  = $addressModel->relation(true)->find($address_id);
                $data['shr_name'] = $addressData['consignee'];
                $data['shr_tel']  = $addressData['mobile'];
                $data['shr_province'] = $addressData['province']['region_name'];
                $data['shr_city']     = $addressData['city']['region_name'];
                $data['shr_area'] = $addressData['district']['region_name'];
                $data['shr_address'] = $addressData['address'];
            }else{
                $this->error = "请选择收货地址";
                return FALSE;
            }

            //收货方式
            $shipping_id = I('post.shipping_id',0);
            $config_option = I('post.config_option');
            if($shipping_id){
                $shippingModel = D('shipping');
                $shippingData = $shippingModel->find($shipping_id);
                $data['shipping_id'] = $shippingData['shipping_id'];
                $data['shipping_name'] = $shippingData['shipping_name'].' '.$config_option[$shipping_id];
                $total_price += $shippingData['insure'];
            }else{
                $this->error="请选择送货方式";
                return FALSE;
            }
            //把其他信息补到订单中
            $data['total_price'] = $total_price;
            $data['member_id']   = $memberId;
            $data['addtime']     = time();
            //发票信息
            if($data['inv_payee'] == 'personal'){
                $data['inv_payee']= '个人';
            }elseif($data['inv_payee']=='company'){
                $data['inv_payee'] = "单位:" . I('post.company_name');
            }
            $this->startTrans();

    }
    //订单编号
    static public function get_order_sn(){
        mt_srand((double)microtime() * 1000000);
        return date('Ymd').str_pad(mt_srand(1,99999),5,'0',STR_PAD_LEFT);
    }
    protected function _after_insert($data,$option){
        $total_price = 0;
        $ogModel = D('order_goods');
        $gnModel = D('goods_number');
        foreach ($option['goods'] as $k => $v){
            $ret = $ogModel->add(
                array(
                    'goods_id'=>$v['goods_id'],
                    'order_id'=>$data['id'],
                    'goods_attr_id'=>$v['goods_attr_id'],
                    'goods_number'=>$v['goods_number'],
                    'price'=>$v['price'],
                ));
            if(!$ret){
                $this->rollback();
                return FALSE;
            }
            $ret = $gnModel->where(
                array(
                    'goods_id'=>array('eq',$v['goods_id']),
                    'goods_attr_id'=>array('eq',$v['goods_number'])
                ))->setDec('goods_number',$v['goods_number']);
            if(FALSE ===$ret){
                $this->rollback();
                return FALSE;
            }
             //所有操作都成功提交事务
            $this->commit();

            //释放锁
            flock($this->fp,LOCK_UN);
            fclose($this->fp);
            //清空购物车
           $cartMode = D('Admin/Cart');
            $cartMode->clear();
        }
    }
    public function search($pageSize= 10){
        $memberId = session('m_id');
        $where['member_id'] =array('eq',$memberId);
        $noPayCount = $this->where(array(
            'member_id'=>array('eq',$memberId),
            'pay_status'=>array('eq','否'),
        ))->count();
        $count = $this->alias('a')->where($where)->count();
        $page = new \Think\Page($count,$pageSize);
        $data['data'] = $this->alias('a')
            ->field('a.id,a.order_status,a.order_sn,a.shr_name,a.total_price,a.addtime,a.pay_status,GROUP_CONCAT(DISTINCT c.sm_logo) logo')
            ->join('LEFT JOIN __ORDER_GOODS__ b ON a.id=b.order_id LEFT JOIN __GOODS__ c ON b.goods_id=c.id')
            ->where($where)
            ->group('a.id')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
            $data['noPayCount'] = $noPayCount;
            return $data;
    }
    public function lst($pageSize= 10){
        $where = array();
        if($pay_status = I('get.pay_status'))
            $where['pay_status'] = array('eq',$pay_status);

        if($post_status = I('get.post_status')){
            if($post_status ==1){
                $where['post.status'] = array('eq',0);
                $where['pay_status']  = array('eq','Y');
            }else{
                $where['post_status'] = array('eq',$post_status);
            }
        }
        //收货人
        if($shr_name = I('get.shr_name'))
            $where['shr_name'] = array('like',"%$shr_name%");
        //电话
        if($shr_tel = I('get.shr_tel'))
            $where['shr_tel'] = array('like','%$shr_tel%');

        //快递单号
        if($post_number = I('get.post_number'))
            $where['post_number'] = array('like',"%" .trim($post_number)."%");

        //下单时间
        if(!empty(I('get.o_fa')) && !empty(I('get.o_ta'))){
            $min = strotime(I('get.o_fa'));
            $max = strtotime(I('get.o_ta'));
            $where['add_time'] = array(array('egt',$min),array('elt',$max));
        }
        //支付时间
        if(!empty(I('get.p_fa')) && !empty(I('get.p_ta'))){
            $min = strtotime(I('get.p_fa'));
            $max = strtotime(I('get.p_fa'));
            $where['pay_time'] = array(array('egt',$min),array('elt',I('get.max_price')));
        }

        $count = $this->alias('a')->where($where)->count();
        $page = new \Think\Page($count,$pageSize);
        $data['data'] = $this->alias('a')
            ->where($where)
            ->group('a.id')
            ->order('a.addtime DESC')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        return $data;
    }
    public function setPaid($orderId){
        $this->where(array(
            'id'=>array('eq',$orderId),
        ))->save(array(
            'pay_status'=>'是',
            'pay_time' => time(),
        ));
        $tp = $this->field('total_price,member_id')->find($orderId);
        $memberModel = M('member');
        $memberModel->where(array(
            'id'=>array('eq',$tp['member_id']),
        ))->select('jifen',$tp['total_price']);
    }
    //取出一个订单详细信息
    public function getDetail($orderId){
        $goodsModel = D('Admin/Goods');
        $goodsAttrModel = D('goods_attr');
        $orderGoodsModel = D('Admin/OrderGoods');
        $orderData = $this->find($orderId);
        $orderData['goods_list'] = $orderGoodsModel->where(array('order_id'=>$orderId))->select();
        foreach($orderData['goods_list'] as $k => &$v){
            $goodsData = $goodsModel->field('goods_name,sm_logo')->find($v['goods_id']);
            $v['goods_name'] = $goodsData['goods_name'];
            $v['sm_logo'] = $goodsData['sm_logo'];
            if($v['goods_attr_id']){
                $v['gaData'] = $goodsAttrModel->alias('a')
                    ->field('a.attr_value,b.attr_name')
                    ->join('LEFT JOIN __ATTRIBUTE__ b ON a.attr_id = b.id')
                    ->where(array(
                        'a.id'=>array('IN',$v['goods_attr_id'])
                    ))->select();
            }
        }
        return $orderData;
    }
}